<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {useRouter} from 'vue-router';
import message, {PositionTypeEnum} from "@/components/message";
import {findUserMenusApi} from "@/api/auth";

const router = useRouter();

// 默认激活的菜单项
const activeMenu = ref('/system/user');

// 菜单数据
const menuData = ref();

// 处理菜单项点击事件
const handleSelect = (index: any) => {
  console.log('Selected menu:', index);
  // 路由跳转
  router.push(index);
};

/**
 * 获取菜单
 */
/**
 * 注册
 */
const findUserMenus = async () => {
  try {
    const res = await findUserMenusApi();
    console.log(res.data);
    menuData.value = res.data;
  } catch (err) {
    console.error(err);
    message.error('系统错误', PositionTypeEnum.TOP);
  }
}

/*
 * 页面加载时预处理
 */
onMounted(() => {
  findUserMenus()
})
</script>

<template>
  <div class="main-root">
    <div class="common-layout">
      <el-container>
        <el-header>Header</el-header>
        <el-container>
          <el-aside width="200px">
            <el-scrollbar>
              <el-menu
                  :default-active="activeMenu"
                  class="el-menu-vertical-demo"
                  @select="handleSelect"
                  background-color="rgb(47, 64, 80)"
              >
                <!-- 递归渲染菜单 -->
                <template v-for="item in menuData" :key="item.menuId">
                  <!-- 如果有子菜单，渲染 el-submenu -->
                  <el-sub-menu
                      v-if="item.childMenu && item.childMenu.length > 0"
                      :index="item.url"
                  >
                    <template #title>
                      <i :class="item.icon"></i>
                      <span>{{ item.menuName }}</span>
                    </template>
                    <!-- 递归渲染子菜单 -->
                    <template v-for="child in item.childMenu" :key="child.menuId">
                      <el-menu-item :index="child.url">
                        <i :class="child.icon"></i>
                        <span>{{ child.menuName }}</span>
                      </el-menu-item>
                    </template>
                  </el-sub-menu>
                  <!-- 如果没有子菜单，渲染 el-menu-item -->
                  <el-menu-item v-else :index="item.url">
                    <i :class="item.icon"></i>
                    <span>{{ item.menuName }}</span>
                  </el-menu-item>
                </template>
              </el-menu>
            </el-scrollbar>
          </el-aside>
          <el-main>Main</el-main>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main-root {
  display: flex;
  flex-direction: column;
  width: 100vw;
  color: rgb(255, 255, 255);
  font-family: "HarmonyOS Sans Thin", sans-serif;

  .el-header {
    background-color: rgb(54, 127, 169); /* 浅蓝色背景 */
  }
}
</style>